<template>
  <el-dialog :model-value="dialogVisible" width="80%" max-width="1000px"
    class="pending-receive-order-select-dialog" @close="handleClose" :close-on-click-modal="false">
       
    <!-- 使用插槽自定义标题 -->
    <template #header="{ titleId, titleClass }">
      <div class="dialog-header">
        <span :id="titleId" :class="titleClass">选择待收款单据</span>
        <span v-if="targetObject" class="sub-title">{{ targetObject.name }}</span>
      </div>
    </template>

    <!-- 搜索栏 
    <el-row>
      <el-col :span="24" style="padding-left: 24px;">
        <el-form :inline="true" :model="filter" class="demo-form-inline">
          <el-form-item label="单据编号">
            <el-input v-model="filter.docCode" placeholder="单据编号" clearable />
          </el-form-item>
          
          <el-form-item label="单据标题">
            <el-input v-model="filter.title" placeholder="单据标题" clearable />
          </el-form-item>

          <el-form-item label="进度状态">
            <el-select v-model="filter.progressState" placeholder="请选择" clearable>
              <el-option label="未开始" :value="ProgressState.None" />
              <el-option label="部分完成" :value="ProgressState.PartDone" />
              <el-option label="全部完成" :value="ProgressState.AllDone" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    -->

    <!-- 操作按钮 -->
    <div style="margin-bottom: 10px; text-align: right;">
      <el-button type="primary" @click="handleBatchSelect">选择选中单据</el-button>
    </div>

    <!-- 数据列表 -->
    <el-table ref="table" v-loading="loading" :data="pendingOrderDataList" style="width: 100%" border
      @selection-change="handleSelectionChange" row-key="id" :row-class-name="rowClassName">
      <el-table-column type="selection" :reserve-selection="true" width="55" :selectable="isSelectable"/>

      <el-table-column prop="docCode" label="单据编号" align="center" width="180" />

      <el-table-column prop="title" label="源单据标题" align="center" show-overflow-tooltip />

      <el-table-column label="客户" align="center" width="120">
        <template #default="scope">
          {{ scope.row.targetObject?.name || '-' }}
        </template>
      </el-table-column>

      <el-table-column label="总金额" align="right" width="100">
        <template #default="scope">
          {{ formatCurrency(scope.row.totalMount) }}
        </template>
      </el-table-column>

      <el-table-column label="已核销" align="right" width="100">
        <template #default="scope">
          {{ formatCurrency(scope.row.totalMount - scope.row.pendingPayMount) }}
        </template>
      </el-table-column>

      <el-table-column label="待核销" align="right" width="100">
        <template #default="scope">
          {{ formatCurrency(scope.row.pendingPayMount) }}
        </template>
      </el-table-column>

      <el-table-column label="进度状态" align="center" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.progressState.code === ProgressState.None.code">未开始</el-tag>
          <el-tag v-else-if="scope.row.progressState.code === ProgressState.PartDone.code" type="warning">部分完成</el-tag>
          <el-tag v-else-if="scope.row.progressState.code === ProgressState.AllDone.code" type="success">全部完成</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="100">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleSelect(scope.row)"
           :disabled="!isSelectable(scope.row)">
            选择</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 20px; text-align: right">
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="fetchPendingOrderData" />
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage } from 'element-plus'
import { FundUiAction } from '../../public/engine/uiAction/fundUiAction'
import { Definition } from '../../public/engine/common/definition'
import { DataPage } from '../../public/network/communicationConverter'
import { Util } from '../../public/utils/util'
import { PendingReceiveOrderFilter } from '../../public/engine/funds/pendingReceiveOrder'
import { ProgressState } from '../../public/engine/common/docDefinition'

export default {
  name: 'PendingReceiveOrderSelectDialog',
  props: {
    fundUiAction: {
      type: Object,
      required: true
    }
  },
  emits: ['select', 'close'],
  data() {
    return {
      dialogVisible: false,
      loading: false,
      pendingOrderDataList: [],
      total: 0,
      selectedItems: [],
      selectedPendingOrders: [], // 已选择的待收款单列表 上级UI 传入
      excludePendingOrders: [],
      filter: new PendingReceiveOrderFilter({}),
      queryParams: {
        pageNum: 1,
        pageSize: Definition.gDefualPageSize
      },
      targetObject: null,
      ProgressState
    }
  },
  methods: {
    // 打开弹窗方法
    open(selectedPendingOrderList, { excludePendingOrders = [], targetObject = null } = {}) {
      this.dialogVisible = true
      this.filter.clear();     
      this.targetObject = targetObject
      if (targetObject) {
        this.filter.targetObjId = targetObject.id
      }
      this.selectedPendingOrders = selectedPendingOrderList || []
      this.excludePendingOrders = excludePendingOrders || []
      this.queryParams.pageNum = 1
      // 清空 selection
      this.$nextTick(() => {
        this.$refs.table?.clearSelection();
      });
      this.fetchPendingOrderData()
    },

    // 判断待收款单是否可选择
    isSelectable(row) {
      // 如果没有排除列表，则所有单据都可选择
      if (!this.excludePendingOrders || this.excludePendingOrders.length === 0) {
        return true;
      }
      
      // 检查当前单据是否在排除列表中
      return !this.excludePendingOrders.some(
        item => item.id === row.id
      );
    },

    async fetchPendingOrderData() {
      try {
        this.loading = true

        const res = await this.fundUiAction.getTargetObjectPendingReceiveOrderData({
          pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize),
          filter: this.filter
        })

        if (res && res.data && res.data.dataList) {
          this.pendingOrderDataList = res.data.dataList
          this.total = res.data.pageInfo.total
        } else if (res.resErr) {
          ElMessage.error('获取待收款单据数据失败: ' + res.resErr)
        }
      } catch (error) {
        console.error('获取待收款单据数据失败:', error)
        ElMessage.error('获取待收款单据数据失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.queryParams.pageNum = 1
      this.fetchPendingOrderData()
    },

    resetSearch() {
      this.filter.clear()
      if (this.targetObject) {
        this.filter.targetObjId = this.targetObject.id
      }
      this.queryParams.pageNum = 1
      this.fetchPendingOrderData()
    },

    formatCurrency(value) {
      return Util.getFundString(value)
    },

    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedItems = selection
    },

    // 批量选择待收款单
    handleBatchSelect() {
      if (this.selectedItems.length === 0) {
        ElMessage.warning('请选择至少一条待收款单据')
        return
      }

      this.$emit('select', this.selectedItems)
      this.handleClose()
    },

    // 单个选择待收款单
    handleSelect(item) {
      this.$emit('select', [item])
      this.handleClose()
    },

    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false
      this.$emit('close')
    },

    rowClassName({ row }) {
      if (
        this.selectedPendingOrders.some(
          item => item.id === row.id
        )
      ) {
        return 'already-selected-row';
      }
      return '';
    },
  }
}
</script>

<style scoped>
/* 添加标题样式 */
.dialog-header {
  display: flex;
  align-items: baseline;
}

.dialog-header span:first-child {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.sub-title {
  margin-left: 12px;
  font-size: 13px;
  color: #909399;
  font-weight: normal;
}
</style>

<style>
.pending-receive-order-select-dialog {
  max-width: 1000px !important;
}

/* 已选择行的样式 */
.already-selected-row td.el-table__cell:first-child {
  background: #d9f0ff !important;
}
</style>